package com.msun.monitor.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.msun.monitor.constant.AlertGroupEnum;
import com.msun.monitor.constant.AlertStatusEnum;
import com.msun.monitor.entity.Alert;
import com.msun.monitor.mapper.AlertMapper;
import com.msun.monitor.service.IAlertService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class AlertServiceImpl implements IAlertService {

    @Resource
    AlertMapper alertMapper;

    @Transactional
    @Override
    public boolean batchInsert(String json) {

        JSONArray array = JSON.parseObject(json).getJSONArray("alerts");
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = array.getJSONObject(i);
            //构造主告警信息
            Alert alert = new Alert();
            alert.parse(object);

            //恢复告警
            if (AlertStatusEnum.RESOLVED.getValue().equals(alert.getStatus())) {
                Alert unFinish = alertMapper.selectUnFinish(alert.getFingerPrint());
                if (unFinish == null) {
                    log.error("状态错误,恢复告警，但未找到触发告警信息,json={}", json);
                    return false;
                }
                //更新恢复状态和恢复时间
                unFinish.setStatus(AlertStatusEnum.RESOLVED.getValue());
                unFinish.setEndAt(alert.getEndAt());
                alertMapper.updateById(unFinish);
            }

            //触发告警,插入主告警信息和子告警信息
            alertMapper.insert(alert);
            insertSubAlert(alert);
        }

        return true;
    }


    private void insertSubAlert(Alert alert) {
        //构造子告警信息
        AlertGroupEnum groupEnum = AlertGroupEnum.match(alert.getAlertGroup());
        if (groupEnum == null) {
            return;
        }

        switch (groupEnum) {
            case PG -> {

            }
        }
    }

}
